<template>
	<view class="login">
		<view class="bg-white flex-sub radius shadow-lg" v-if="status">
			<image src="../../static/Hicon/loading-white.gif" mode="aspectFit" class="gif-white response"
				style="height:240upx"></image>
		</view>
		<!-- <radio-modal ref='radioModal'>sadasd</radio-modal> -->
	</view>
</template>

<script>
	import ls from '../../utils/local.js'
	import {
		login,
		mbLogin,
		getCurrentUser,
		queryNewsById,
		queryNewsApplyById,
		loginDinkTalk
	} from '../../api/service.js'
	import radioModal from '../basic/radio-modal'
	import * as dd from 'dingtalk-jsapi';

	export default {

		data() {
			return {
				optionName: '--',
				//22017081IZER20240909
				userNo: '',
				// userNo:'',
				realname: '--',
				status: false,
				id: '',
				contractName: '',
				crruentType: '',
				processId: '',
				entityId: '',
				processStatus: '',
				applyTitle: '',
				type: '',
				error: '',
				code: ''
			};
		},

		onLoad(option) {
			// alert("测试")
			// this.getddCode();
			// localStorage.clear()
			this.status = true;
			// this.getUserInfor(option.token)
			// this.getUserInfor()
			// this.SSOLogin()
			this.contractName = option.contractName
			this.crruentType = option.crruentType
			this.processId = option.processId
			this.processStatus = option.processStatus
			this.applyTitle = option.applyTitle
			this.type = option.type
			this.entityId = option.id
			this.code = option.code
			var _this = this;
			localStorage.clear()


			// 测试环境放开这段代码
			console.log(this.userNo)
			// _this.userNo=option.userNo
			this.status = true;
			// _this.SSOLogin()
			// =====正式环境放开这段代码=========

			// uni.request({
			// 	url: '/wechat/wx/userNo/' + option.code,
			// 	success: (res) => {
			// 		_this.userNo = res.data;
			// 		_this.SSOLogin()
			// 	}
			// })
			// console.log("option.id" + option.id)
		},
		mounted() {
			// alert('初始化钉钉code')
		   this.initDingTalkLogin();
		// 	alert("获取钉钉Code")

		// 	//进行钉钉登录操作
		// 	dd.ready(() => {
		// 		alert("进入钉钉");
		// 		dd.runtime.permission.requestAuthCode({
		// 			corpId: 'ding5afe027889e9ac43acaaa37764f94726', // 使用 this 访问 data 中的 corpId
		// 			onSuccess: (info) => {
		// 				alert("code" + info.code)
		// 				this.getUserInfor(info.code)
		// 			},
		// 			onFail: (error) => {
		// 				this.userCode += " 获取授权码失败 ";
		// 				alert('好吧，问题不小');
		// 				this.$Message.error(JSON.stringify(error));
		// 				alert("错误" + JSON.parse(error))
		// 			}
		// 		});
		// 	});
		// },
		// alert('初始化钉钉code')
		//    this.initDingTalkLogin();
		},

		onHide() {},
		onShow() {

			// if (ls.get('mToken')) {
			// 	uni.navigateTo({
			// 		url: '../index/index'
			// 	})
			// } else {
			// 	window.onload()
			// }
		},
		methods: {


			initDingTalkLogin() {

				 dd.ready(() => {
				              dd.runtime.permission.requestAuthCode({
				                corpId: 'ding5afe027889e9ac43acaaa37764f94726', // 企业id
				                onSuccess: (info) => {
				                  //todo: 测试获取授权码
								  // alert("获取授权码==="+info.code)
								  this.getUserInfor(info.code)
				                },
				                onFail: (error) => {
				                  this.userCode += " 获取授权码失败 ";
				      //             alert('好吧，问题不小')
								  // alert(JSON.stringify(error))
				                  this.$Message.error(JSON.stringify(error))
				                }
				              });
							  })
			getUserInfor(code) {
				// alert("获取code"+code)
				loginDinkTalk({
					code: code,
					appkey: "dingbtrk790i40tubrfe",
					appsecret: "qIll_OftileW_aR_KMpMZfYAn8hXmRX7qZBX_04lJmTtl-kHVyWYKQhbzRtpGPAr"
				}).then(res => {
					if (res.success == true) {
						// alert("res"+JSON.stringify(res))
						this.userNo = res.result
						// alert('获取的工号'+this.userNo)
						this.SSOLogin()
					}
				})
			},
			getFormattedDate() {
				const date = new Date();
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}${month}${day}`; // 格式化为 YYYY-MM-DD
			},
			SSOLogin() {
				// alert('开始登陆'+this.userNo)
				var _this = this;
				login({
					'userNo': this.userNo + 'IZER' + this.getFormattedDate()
				}).then(res => {
					if (res.success) {
						ls.set('mUserInfo', res.result.userInfo);
						ls.set('mToken', res.result.token);
						ls.set('Listdeparts', res.result.departs)
						getCurrentUser().then(currentUserRes => {
							// 将对象转换为字符串
							// const userInfo = JSON.stringify(currentUserRes, null, 2);
							ls.set('departs', currentUserRes.result.orgName);
						}).catch(error => {
							// alert('获取用户信息失败: ' + error.message);
						});
						if (res.result.multi_depart == 2) {
							var currentDepart = res.result.departs.filter(item => {
								return item.orgCode == res.result.userInfo.orgCode
							})
							ls.set('departs', currentDepart[0].departName)
						} else {
							if (res.result.multi_depart == 1) {
								ls.set('departs', res.result.departs[0].departName)
							} else {
								ls.set('departs', '暂无')
							}

						}

						setTimeout(function() {
							uni.showToast({
								title: '欢迎登录成功！',
								duration: 2000,
								success: function() {
									_this.status = false
									console.log("this.type===" + _this.type)
									if (_this.type != undefined) {
										// alert("this.type==="+this.type)
										if (_this.type == '1') {
											console.log("this.type===" + _this.type)
											//合同
											queryNewsById({
												id: _this.id
											}).then(res => {
												uni.navigateTo({
													url: '../component/query-custom/new-module2?id=' +
														_this.id + '&title=' +
														res.result
														.contractName +
														'&isApprove=' + this
														.crruentType +
														'&pId=' + res.result
														.processId +
														'&processStatus=' + res
														.result
														.processStatus
												});
											})

											//零星付款
										} else if (_this.type == '2') {
											uni.navigateTo({
												url: '../component/query-custom/new-module1?id=' +
													item.id + '&title=' + item
													.applyTitle +
													'&isApprove=' + _this.crruentType +
													'&pId=' + item.processId +
													'&processStatus=' + item
													.processStatus
											});
											//合同付款
										} else if (_this.type == '3') {
											// alert("id" + _this.entityId)
											// alert("type" + _this.type)
											queryNewsApplyById({
												id: _this.entityId
											}).then(res => {
												var url =
													'../component/query-custom/news-module?id=' +
													_this.id + '&title=测试' +
													'&isApprove=1' +
													'&pId=' + res.result.processId +
													'&processStatus=' + res.result
													.processStatus
												// alert("URL" + url)
												uni.navigateTo({
													url: '../component/query-custom/new-module2?id=' +
														_this.entityId +
														'&title=测试' +
														'&isApprove=0' +
														'&pId=' + res.result
														.processId +
														'&processStatus=' + res
														.result
														.processStatus
												});
											})

										}

									} else {
										uni.navigateTo({
											url: '../index/index'
										})
									}
								}
							});

						}, 1200)

					} else {
						uni.showToast({
							title: res.message,
							duration: 2000
						});
					}

				})

			}
		}
	}
</script>

<style lang="scss">
	.login {
		// display: flex;
		justify-content: center;
		min-height: 100%;
		background: #fff;
		align-items: center;
		// line-height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;

		.flex-sub {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			z-index: 10;
			width: 400rpx;
			height: auto;
		}
	}
</style>